package cn.edu.scnu.service;

import cn.edu.scnu.entity.Flower;
import cn.edu.scnu.mapper.FlowerMapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import jakarta.annotation.Resource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.Flow;

@Service
public class FlowerService extends ServiceImpl<FlowerMapper, Flower> {

    @Resource
    @Autowired
    private FlowerMapper flowerMapper;
    @Autowired
    private RedisTemplate redisTemplate;
    @Cacheable(value = "fclass-cache", key = "'fclass-list'")
    public List<String> findfclass() {
        QueryWrapper<Flower> queryWrapper = new QueryWrapper<>();
        queryWrapper.select("distinct fclass");
        List<Flower> flowerList = flowerMapper.selectList(queryWrapper);
        List<String> fclasslist = new ArrayList<>();
        for (Flower flower : flowerList) {
            fclasslist.add(flower.getFclass());
        }
        return fclasslist;
    }

    public Map<String, Object> queryPage(String fname,String fclass,Integer minprice,Integer maxprice, Integer pageNo, Integer pageSize) {
        QueryWrapper<Flower> queryWrapper = new QueryWrapper<>();
        if(!"".equals(fname)&&fname!="")queryWrapper.like("fname",fname);
        if(!"".equals(fclass)&&fclass!="")queryWrapper.eq("fclass",fclass);
        queryWrapper.between("yourprice",minprice,maxprice);
        queryWrapper.orderByDesc("sellednum");
        int count = flowerMapper.selectCount(queryWrapper).intValue();
        // 构建分页对象（第一个参数是当前页数，第二个参数是每页条数）
        Page<Flower> page = new Page<Flower>(pageNo, pageSize);
        Page<Flower> flowerPage = flowerMapper.selectPage(page, queryWrapper);

        Map<String, Object> map = new HashMap<>();
        map.put("count", count);
        map.put("recourds", page.getRecords());
        return map;
    }


    public Flower findFlowerById(String flowerid) {
        Object object=redisTemplate.opsForValue().get("flower_"+flowerid);
        if(object!=null) {
            return (Flower) object;
        }else {
            Flower flower=flowerMapper.selectById(flowerid);
            redisTemplate.opsForValue().set("flower_"+flowerid,flower);
        return  flower;

    }}

    public void updateFlowerById(Flower flower) {
        flowerMapper.updateById(flower);
        redisTemplate.opsForValue().set("flower_"+flower.getFlowerid(),flower);
    }
}
